package com.hyperfix.simulator.timer;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hyperfix.models.simulator.pojos.FlowTable;
import com.hyperfix.models.simulator.pojos.ScheduleSetting;
import com.hyperfix.simulator.mapper.FlowTableMapper;
import com.hyperfix.simulator.senor.CombinationSenor;
import com.hyperfix.simulator.mapper.SysJobMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author JiangChunYu
 * 2024/3/12
 */
@Slf4j
@Component
public class SysJobInitializer implements CommandLineRunner {
    @Resource
    private CronTaskRegistrar cronTaskRegistrar;
    @Resource
    private FlowTableRegistrar flowTableRegistrar;
    @Resource
    private SysJobMapper sysJobMapper;
    @Resource
    private FlowTableMapper flowTableMapper;

    @Override
    public void run(String... args) {
        loadFlowTables();
        loadSchedules();
    }

    /**
     * 加载流量表
     */
    private void loadFlowTables() {
        List<FlowTable> flowTableList = flowTableMapper.selectList(new LambdaQueryWrapper<>());
        if (CollectionUtils.isNotEmpty(flowTableList)) {
            for (FlowTable flowTable : flowTableList) {
                flowTableRegistrar.addFlowTable(flowTable.getPipelineId(), flowTable);
            }
            log.info("流量表已加载完毕...");
        }
    }

    /**
     * 加载定时任务
     */
    private void loadSchedules() {
        List<ScheduleSetting> jobList = sysJobMapper.selectAll();
        if (CollectionUtils.isNotEmpty(jobList)) {
            for (ScheduleSetting job : jobList) {
                CombinationSenor senor = new CombinationSenor(job.getStation(), job.getPipeline());
                SysJob sysJob = new SysJob(job.getJobId(), senor);
                cronTaskRegistrar.addCronTask(sysJob, job.getCronExpression());
            }
            log.info("定时任务已加载完毕...");
        }
    }
}
